/**
 * 计时器仪表盘
 * 命名空间 "scene-timer"
 * 
 * @author Zdream
 * @since 0.2.3
 */

let handler;

function create (context) {
  return {
    template : context.template,
    data : function () {
      return {
        status : null,
        timeText : ''
      }
    },
    props : {
      sid : String,
    },
    methods : {
      timeTextRefresh : function () {
        if (!this.status) {
          return;
        }

        let data = this.status.data;
        let figure;
        if (!data.player || data.pause) {
          figure = parseInt(data.delta / 10);
        } else {
          let now = new Date().getTime();
          let start = this.status.instant.getTime();
          figure = parseInt((parseInt((now - start) / 100) + data.delta) / 10);
        }

        if (figure < 60) {
          this.timeText = `${figure} 秒`;
        } else if (figure < 3600) {
          this.timeText = `${parseInt(figure/60)} 分 ${figure%60} 秒`;
        } else {
          let hour = parseInt(figure/3600);
          let min = parseInt((figure - hour * 3600) / 60);
          this.timeText = `${hour} 小时 ${min} 分 ${figure%60} 秒`;
        }
      },
      // ****** 以下是 timer 要触发的六个事件
      // 1. 开始
      // 2. 结束
      // 3. 暂停
      // 4. 重置（到 0 或指定时间）
      // 5. 计次
      // 6. 撤销暂停 / 撤销结束
      commandStart : function () {
        context.sendCommand(this.sid, 'start');
      },
      commandStop : function () {
        context.sendCommand(this.sid, 'stop');
      },
      commandPause : function () {
        context.sendCommand(this.sid, 'pause');
      },
      commandReset : function () {
        context.sendCommand(this.sid, 'reset');
      },
      commandCount : function () {
        context.sendCommand(this.sid, 'count');
      },
      commandUndoPause : function () {
        context.sendCommand(this.sid, 'undoPause');
      },
      // 监听事件部分
      onScreenUpdated : function () {
        this.status = context.getStatus(this.sid);
      },
    },
    mounted : function () {
      this.status = context.getStatus(this.sid);
      handler = setInterval(this.timeTextRefresh, 100);
      context.getBus().$on('screen-status-sync-all', this.onScreenUpdated);
      context.getBus().$on('screen-updated', this.onScreenUpdated);
      context.getBus().$on('screen-destroyed', this.onScreenUpdated);
    },
    destroyed : function () {
      clearInterval(handler);
      context.getBus().$off('screen-status-sync-all', this.onScreenUpdated);
      context.getBus().$off('screen-updated', this.onScreenUpdated);
      context.getBus().$off('screen-destroyed', this.onScreenUpdated);
    }
  }
}

export default create;
